from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer, BadData

from users.constants import EXPIRES_IN
from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt token扩展登录视图响应数据的函数
    """
    return {
        'username': user.username,
        'user_id': user.id,
        'token': token
    }


# 自定义Django认证后端类
class UsernameMobileAuthBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        :param username: 用户名或者手机号
        :param password: 密码
        """
        # 根据用户名或者手机号查询用户的信息
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
        except User.DoesNotExist:
            return None

        # 如果用户存在，再校验密码
        if user.check_password(password):
            return user


def generate_find_password_accesstoken(mobile):
    """
    使用itsdangerous模块，生成加密后的access_token
    """

    secret_key = settings.SECRET_KEY

    serializer = TJWSSerializer(secret_key, EXPIRES_IN)

    access_token = serializer.dumps({'secret_key': mobile})

    return access_token.decode()


def decode_accesstoken(req_data):

    secret_key = settings.SECRET_KEY

    serializer = TJWSSerializer(secret_key)

    try:
        res_dict = serializer.loads(req_data)
    except BadData:
        return None

    return res_dict